import uvicorn
from tortoise.contrib.fastapi import register_tortoise
import traceback
from contextlib import asynccontextmanager
from fastapi import FastAPI
from api.judge import app_judge
import auxi.aux as ax
from debate_orm import RoundTeam, Team, Contest, Rounds


@asynccontextmanager
async def lifespan(apps: FastAPI):
    # Startup
    print("=== 应用启动 ===")

    # 检查是否已有数据
    existing_teams = await Team.all().count()
    if existing_teams > 0:
        print(f"已有 {existing_teams} 支队伍，跳过初始化")
    else:
        try:
            team_counts = 20
            about = ax.generate_table(team_counts)
            print(f"生成比赛数据: {about}")

            await save_participants()  # 主要的造表存表函数

        except Exception as e:
            print(f"初始化失败: {e}")

    yield  # 这里应用正常运行

    # Shutdown
    print("=== 应用关闭 ===")

app = FastAPI(lifespan=lifespan)
app.include_router(app_judge)
register_tortoise(
    app,
    db_url="mysql://root:17368894921ABc@localhost:3306/debate_drive",  # 自用
    modules={"models": ["debate_orm"]},
)


async def reset_database():
    """清空所有数据"""
    await RoundTeam.all().delete()
    await Rounds.all().delete()
    await Team.all().delete()
    await Contest.all().delete()
    print("数据库已重置")


async def save_participants():
    existing_data = await Contest.all().first()
    if existing_data:
        print("数据已初始化，跳过执行")
        return
    try:
        team_counts = 20  # 这里可以调整队伍数量
        about = ax.generate_table(team_counts)

        await reset_database()
        print("=== 开始导入数据 ===")

        # 创建赛场
        contests = {}
        for contest_id in range(1, 7):
            contest = await Contest.create(contest_id=contest_id)
            contests[contest_id] = contest

        # 创建所有需要的轮次
        for round_id in [1, 2, 3]:
            for contest_id in range(1, 7):
                # 检查是否已存在
                existing = await Rounds.filter(round_id=round_id, contest_id=contest_id).first()
                if not existing:
                    await Rounds.create(round_id=round_id, contest_id=contest_id)
                    print(f"创建: 轮次{round_id} - 赛场{contest_id}")
                else:
                    print(f"已存在: 轮次{round_id} - 赛场{contest_id}")

            # 处理队伍数据
        for round_num in [1, 2, 3]:
            rounds_data = about[
                "first_round" if round_num == 1 else "second_round" if round_num == 2 else "third_round"]

            for group_index, match_group in enumerate(rounds_data):
                contest_id = group_index + 1
                contest = contests[contest_id]

                # 获取Rounds记录
                """
                防御性编程：确保轮次和赛场的组合存在
                这种情况不应该发生，
                但以防万一，还是加个检查
                """
                round_obj = await Rounds.filter(round_id=round_num, contest=contest).first()
                if not round_obj:
                    round_obj = await Rounds.create(round_id=round_num, contest=contest)

                position = 1
                for team_id in match_group:
                    if round_num == 1:
                        # 第一轮：创建队伍
                        existing_team = await Team.filter(team_id=team_id).first()
                        if not existing_team:
                            team = await Team.create(team_id=team_id)
                        else:
                            team = existing_team
                    else:
                        # 其他轮次：使用现有队伍进行关联
                        team = await Team.get(team_id=team_id)

                    await RoundTeam.create(round=round_obj, team=team, position=position)
                    position = position % 4 + 1  # 循环位置保持1-4

        print(f"成功导入 {team_counts} 支队伍的比赛数据")
    except Exception as e:
        print(f"导入比赛数据时发生错误: {str(e)}")
        traceback.print_exc()


if __name__ == "__main__":
    uvicorn.run("main:app", host="127.0.0.1", port=8000, log_level="debug", reload=True)
